<script setup name="Post" lang="ts">
import { parseTime } from '../../../utils/ruoyi.ts'
import { addPost, delPost, getPost, listPost, updatePost } from '@/api/system/post'
import type { PostForm, PostQuery, PostVO } from '@/api/system/post/types'

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'))
const message = useMessage()
const modal = useModal()
const postList = ref<PostVO[]>([])
const loading = ref(true)
const ids = ref<Array<number | string>>([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)

const postFormRef = ref()

const dialog = reactive<DialogOption>({
  visible: false,
  title: '',
})

const initFormData: PostForm = {
  postId: undefined,
  postCode: '',
  postName: '',
  postSort: 0,
  status: '0',
  remark: '',
}

const data = reactive<PageData<PostForm, PostQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    postCode: '',
    postName: '',
    status: undefined,
  },
  rules: {
    postName: [{ required: true, message: '岗位名称不能为空', trigger: 'blur' }],
    postCode: [{ required: true, message: '岗位编码不能为空', trigger: 'blur' }],
    postSort: [{ required: true, message: '岗位顺序不能为空', trigger: 'blur' }],
  },
})

const { queryParams, form, rules } = toRefs<PageData<PostForm, PostQuery>>(data)

/** 查询岗位列表 */
async function getList() {
  loading.value = true
  const res = await listPost(queryParams.value)
  postList.value = res.rows
  total.value = res.total
  loading.value = false
}

/** 取消按钮 */
function cancel() {
  reset()
  dialog.visible = false
}

/** 表单重置 */
function reset() {
  form.value = { ...initFormData }
  postFormRef.value?.resetFields()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 多选框选中数据 */
function handleSelectionChange(selection: PostVO[]) {
  ids.value = selection.map(item => item.postId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  dialog.visible = true
  dialog.title = '新增岗位'
}

/** 修改按钮操作 */
async function handleUpdate(row?: PostVO) {
  reset()
  const postId = row?.postId || ids.value[0]
  const res = await getPost(postId)
  Object.assign(form.value, res.data)
  dialog.visible = true
  dialog.title = '修改岗位'
}

/** 提交按钮 */
function submitForm() {
  postFormRef.value?.validate().then(async () => {
    form.value.postId ? await updatePost(form.value) : await addPost(form.value)
    form.value.postId ? message.success('修改成功') : message.success('保存成功')
    dialog.visible = false
    await getList()
  }).catch()
}

/** 删除按钮操作 */
async function handleDelete(row?: PostVO) {
  const postIds = row?.postId || ids.value
  modal.confirm({
    title: `确认删除岗位[${row?.postName}]？`,
    onOk: async () => {
      await delPost(postIds)
      message.success('删除成功')
      await getList()
    },
  })
}

onMounted(() => {
  getList()
})
</script>

<template>
  <div class="p-2">
    <a-card class="mb-20px">
      <bh-table-title v-model:value="queryParams.postName" :show-filtering="false" placeholder="输入岗位名称，按回车键搜索" @show-modal="handleAdd" @on-query="handleQuery" />
    </a-card>
    <a-card>
      <a-table :loading="loading" :pagination="false" :data-source="postList" @selection-change="handleSelectionChange">
        <a-table-column title="岗位名称" align="left" data-index="postName" />
        <a-table-column title="岗位编码" align="center" data-index="postCode" />
        <a-table-column title="状态" align="center" data-index="status">
          <template #default="{ record }">
            <bh-dict-tag :options="sys_normal_disable" :value="record.status" />
          </template>
        </a-table-column>
        <a-table-column title="创建时间" align="center" data-index="createTime" width="180">
          <template #default="{ record }">
            <span>{{ parseTime(record.createTime) }}</span>
          </template>
        </a-table-column>
        <a-table-column title="操作" align="center" width="160" class-name="small-padding fixed-width">
          <template #default="{ record }">
            <a-space :size="20">
              <span
                v-hasPermi="['system:post:edit']"
                class="op-span" type="link"
                @click="handleUpdate(record)"
              >
                <bh-icon type="icon-bianji-copy" />
                <span>编辑</span>
              </span>
              <span
                v-hasPermi="['system:post:remove']"
                class="op-span" type="link"
                @click="handleDelete(record)"
              >
                <bh-icon
                  type="icon-huishouzhan-copy"
                />
                <span>删除</span>
              </span>
            </a-space>
          </template>
        </a-table-column>
      </a-table>
      <div class="text-right mt-20px">
        <a-pagination
          v-show="total > 0"
          v-model:current="queryParams.pageNum" v-model:pageSize="queryParams.pageSize" :total="total"
          show-less-items @change="getList"
        />
      </div>
    </a-card>

    <!-- 添加或修改岗位对话框 -->
    <a-modal v-model:open="dialog.visible" :mask-closable="false" :keyboard="false" :title="dialog.title" destroy-on-close width="500px" append-to-body>
      <a-form ref="postFormRef" :model="form" :rules="rules" :hide-required-mark="true" layout="vertical" class="block-form mt-20px">
        <div class="pl-8px pr-8px">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="岗位名称" prop="postName" class="required">
                <a-input v-model:value="form.postName" placeholder="请输入岗位名称" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="岗位编码" prop="postCode" class="required">
                <a-input v-model:value="form.postCode" placeholder="请输入编码名称" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="岗位顺序" prop="postSort">
                <a-input-number v-model:value="form.postSort" :controls="false" style="width: 100%" controls-position="right" :min="0" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="岗位状态" prop="status">
                <a-radio-group v-model:value="form.status">
                  <a-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value" :label="dict.value">
                    {{ dict.label }}
                  </a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <a-form-item label="备注" prop="remark">
          <a-textarea v-model:value="form.remark" :maxlength="200" placeholder="请输入内容" />
        </a-form-item>
      </a-form>
      <template #footer>
        <div class="dialog-footer">
          <a-button @click="cancel">
            取 消
          </a-button>

          <a-button type="primary" @click="submitForm">
            确 定
          </a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<style scoped lang="less">
@import "@/components/bh-table/index.less";
:deep(.ant-table-empty){
  .ant-table-cell{
    background: #f0f2f5;
  }
  .ant-table-placeholder:hover > td{
    background: #f0f2f5 !important;
  }
}

.op-span{
  cursor: pointer;
  *{
    font-size: 12px;
    color: var(--bh-color-9);
  }
  span{
    padding-left: 5px;
  }

}
:deep(.op-span){
  .ant-switch-checked{
    background: #00DBB3
  }
}
</style>
